/*
 * Shooter.cpp
 *
 *  Created on: Sep 30, 2012
 *      Author: Administrator
 */

#include "Shooter.h"
#include "Util.h"
#include "ShotMemoryStore.h"
#include "Beholder.h"

using namespace Osp::Media;
using namespace Osp::Io;
using namespace Osp::Base;
using namespace Osp::Base::Runtime;
using namespace Osp::Graphics;

Shooter::Shooter() {
	stateChanged = false;
	state = 1;
	delay = 2000;
	store = Util::GetShotStore();
	camera = new Camera();
	result r = E_SUCCESS;
	AppLog("Camera created");
	r = camera -> Construct(*this, CAMERA_PRIMARY);
	AppLog("Camera constructed - %S", GetErrorMessage(r));
	r = camera -> PowerOn();
	AppLog("Camera turned on %S", GetErrorMessage(r));
	r = camera -> StartPreview(null, false);
	AppLog("Camera started preview %S", GetErrorMessage(r));
	Construct();
	Start();
	SendUserEvent(1, null);
}

Shooter::~Shooter() {
	// TODO Auto-generated destructor stub
}

void
Shooter::OnCameraAutoFocused (bool completeCondition) {
	AppLogDebug("Camera auto focused");
}

void
Shooter::OnCameraCaptured (Osp::Base::ByteBuffer &capturedData, result r) {
	AppLogDebug("Camera captured");
	store->StoreShotN(capturedData);
	SendUserEvent(1, null);
}

void
Shooter::OnCameraErrorOccurred (Osp::Media::CameraErrorReason r) {
	AppLogDebug("Camera error");
}

void
Shooter::OnCameraPreviewed (Osp::Base::ByteBuffer &previewedData, result r) {
	AppLogDebug("Camera previewed");
}

result
Shooter::Construct(void) {
	result r = E_SUCCESS;
	r = Thread::Construct(THREAD_TYPE_EVENT_DRIVEN);
	return r;
}

bool
Shooter::OnStart(void) {
	AppLog("Shooter started");

	return true;
}

void
Shooter::OnStop(void) {
	AppLog("Shooter stopping");
	camera -> StopPreview();
	camera -> PowerOff();
}

void
Shooter::OnUserEventReceivedN(RequestId requestId, Osp::Base::Collection::IList *pArgs) {
	Thread::GetCurrentThread()->Sleep(delay);
	result r = E_SUCCESS;
	r = camera -> StartPreview(null, false);
	AppLogDebug("Camera started preview %S", GetErrorMessage(r));
	camera -> SetBrightness(7);
	//camera -> SetIsoLevel(CAMERA_ISO_50);
	if (stateChanged) {
		if (state == 0) {
			delay = 1500;
			camera -> SetQuality(CAMERA_QUALITY_NORMAL);
			camera -> SetCaptureResolution(Dimension(320,240));
		} else if (state == 1) {
			delay = 5000;
			camera -> SetQuality(CAMERA_QUALITY_FINE);
			camera -> SetCaptureResolution(Dimension(1600,1200));
		} else if (state == 2) {
			delay = 5000;
			camera -> SetQuality(CAMERA_QUALITY_SUPER_FINE);
			camera -> SetCaptureResolution(Dimension(2048,1536));
		}
		stateChanged = false;
	}
	camera -> Capture();
	AppLogDebug("Camera captures photo");
}

void
Shooter::setState(int pState) {
	state = pState;
	stateChanged = true;
}

int
Shooter::getState(void) {
	return state;
}
